package com.ohos.fresco.demo;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Window;
import ohos.bundle.AbilityInfo;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import com.facebook.fresco.helper.utils.DensityUtil;
import com.facebook.fresco.helper.utils.ImageFileUtils;
import com.facebook.fresco.helper.utils.MLog;

import java.io.IOException;
import java.io.InputStream;

/**
 * gif的能力
 *
 * @author dev
 * @date 2021-08-20
 */
public class GifAbility extends Ability {
    private static final String LANDSCAPE = "LANDSCAPE";
    private Component emptyComponent;
    private EventHandler eventHandler;
    private Image simpleDraweeView;
    private int count = 0;

    @Override
    public void onStart(Intent intent) {
        Window window = getWindow();
        window.setStatusBarColor(Color.getIntColor("#313A99"));
        window.setStatusBarVisibility(Component.VISIBLE);
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_fresco_gif);

//       SimpleDraweeView  simpleDraweeView = (SimpleDraweeView) findComponentById(ResourceTable.Id_sdv_1);
//        ImageLoader.loadImage(simpleDraweeView, url);
        // 依赖库 fresco 加载GIF图功能有缺陷,故用下方实现方式
        simpleDraweeView = (Image) findComponentById(ResourceTable.Id_iv_thumbnail);
        emptyComponent = findComponentById(ResourceTable.Id_emptyComponent);

        ComponentContainer.LayoutConfig layoutConfig = simpleDraweeView.getLayoutConfig();
        layoutConfig.width = DensityUtil.vp2px(this, 300);
        layoutConfig.height = DensityUtil.vp2px(this, 300);
        simpleDraweeView.setLayoutConfig(layoutConfig);

        ComponentContainer.LayoutConfig layoutConfig1 = emptyComponent.getLayoutConfig();
        if (DensityUtil.getDisplayWidth(this) < DensityUtil.getDisplayHeight(this)) { // 竖屏
            layoutConfig1.height = (int) (DensityUtil.getDisplayHeight(this) / 4);
        } else {
            layoutConfig.height = 0;
        }
        emptyComponent.setLayoutConfig(layoutConfig1);

        simpleDraweeView.setPixelMap(ResourceTable.Media_icon_dog_and_cat);
        eventHandler = new EventHandler(EventRunner.getMainEventRunner());
        eventHandler.sendEvent(innerEvent);
    }

    final InnerEvent innerEvent = InnerEvent.get(new Runnable() {
        @Override
        public void run() {
            if (count >= 39) {
                count = 0;
            }
            simpleDraweeView.setPixelMap(ImageFileUtils.getPixelMap(getContext(), ResourceTable.Media_icon_dog_and_cat, count));
            simpleDraweeView.postLayout();
            count++;
            eventHandler.sendEvent(InnerEvent.get(this), 20);
        }
    });

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        String name = displayOrientation.name();
        ComponentContainer.LayoutConfig layoutConfig = emptyComponent.getLayoutConfig();
        if (LANDSCAPE.equals(name)) { // 横屏
            layoutConfig.height = 0;
        } else { // 竖屏
            layoutConfig.height = (int) (DensityUtil.getDisplayHeight(this) / 4);
        }
        emptyComponent.setLayoutConfig(layoutConfig);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (eventHandler != null) {
            eventHandler.removeAllEvent();
        }
    }

    /**
     * 查找本地资源图片
     *
     * @param resId res id
     * @param index 像素帧
     * @return {@link PixelMap}
     */
    private PixelMap getPixelMap(int resId, int index) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = getResourceManager().getResource(resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/gif";
            ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            PixelMap pixelMap = imageSource.createPixelmap(index, decodingOptions);
            return pixelMap;
        } catch (IOException | NotExistException error) {
            MLog.error("GifAbility getPixelMap IOException " + error.getLocalizedMessage());
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (IOException error) {
                MLog.error("GifAbility getPixelMap finally IOException " + error.getLocalizedMessage());
            }
        }
        return null; // 返回空
    }
}
